package com.pactera.util;

import com.sun.mail.util.MailSSLSocketFactory;

import javax.mail.Address;
import javax.mail.Message;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Date;
import java.util.Properties;
import java.util.concurrent.atomic.AtomicReference;

/**
 * Created by Pactera on 2017/1/9.
 */
public class JavaMailSender {

    public static void  sendMail(String toEmailAddress,String emailTitle,String emailContent)throws Exception{
        Properties props = new Properties();

        //todo 开启debug调试
        props.setProperty("mail.debug", "true");
        //todo 发送服务器需要身份验证
        props.setProperty("mail.smtp.auth", "true");
        //todo 设置邮件服务器主机名
        props.setProperty("mail.host", "smtp.qq.com");
        //todo 发送邮件协议名称
        props.setProperty("mail.transport.protocol", "smtp");

        /**SSL认证，注意腾讯邮箱是基于SSL加密的，所有需要开启才可以使用**/
        MailSSLSocketFactory sf = new MailSSLSocketFactory();
        sf.setTrustAllHosts(true);
        props.put("mail.smtp.ssl.enable", "true");
        props.put("mail.smtp.ssl.socketFactory", sf);

        //todo 创建会话
        Session session = Session.getInstance(props);

        //todo 发送的消息，基于观察者模式进行设计的
        Message msg = new MimeMessage(session);
        msg.setSubject(emailTitle);
        //todo 使用StringBuilder，因为StringBuilder加载速度会比String快，而且线程安全性也不错
        AtomicReference<StringBuilder> builder = new AtomicReference<StringBuilder>(new StringBuilder());
        builder.get().append("\n"+emailContent);
        builder.get().append("\n时间 " + new Date());
        msg.setText(builder.get().toString());
        msg.setFrom(new InternetAddress("你的QQ邮箱"));

        Transport transport = session.getTransport();
        transport.connect("smtp.qq.com", "你的QQ邮箱", "你开启SMTP服务申请的独立密码");
        //todo 发送消息
        transport.sendMessage(msg, new Address[] { new InternetAddress(toEmailAddress) });
        transport.close();
    }
}